package com.wangzy.flutterandroid

import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.widget.RelativeLayout
import com.wangzy.flutterandroid.databinding.ActivityMainBinding
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.EventChannel.EventSink
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.StringCodec
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : FlutterActivity() {


    private lateinit var binding: ActivityMainBinding
    private lateinit var basicMessageChannel: BasicMessageChannel<String>

    private lateinit var eventChannel: EventChannel
    private var eventSink: EventSink? = null;

    private lateinit var methodChanel:MethodChannel;

    private val tag = "test";


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.buttonTest.setOnClickListener {

            //方法1，直接跳转到 flutter activity页面
            /* startActivity(
                 FlutterActivity.
                 withNewEngine().
                 initialRoute("/").
                 build(this@MainActivity)
             );
             */

            //方法2.使用FlutterView
            var flutterView = FlutterView(this@MainActivity);
//            var flutterEngin=FlutterEngine(this@MainActivity);
//            flutterEngin?.getDartExecutor()?.executeDartEntrypoint(
//                DartExecutor.DartEntrypoint.createDefault()
//            );
            /* // 1. 设置初始路由
             flutterEngine?.getNavigationChannel()?.setInitialRoute("/anotherRoute");
             // 2. 开始执行Dart代码以预热FlutterEngine
             flutterEngine?.getDartExecutor()?.executeDartEntrypoint(
                 DartExecutor.DartEntrypoint.createDefault()
             );*/
            var rlp = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            flutterView.attachToFlutterEngine(flutterEngine!!);
            binding.relativeLayoutFlutter.addView(flutterView, rlp);
        }

        binding.buttonSendEvent.setOnClickListener {
            var sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sendEventToFlutter("FK" + sdf.format(Date()))
        }

    }

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        configBasicMessageChannel();
        configEventChannel();
        configMethodChannel();
    }

    private fun configEventChannel() {
        try {
            eventChannel = EventChannel(flutterEngine!!.dartExecutor.binaryMessenger, "com.test.event/channel")
            // 设置流处理器
            eventChannel.setStreamHandler(object : EventChannel.StreamHandler {

                override fun onListen(arguments: Any?, events: EventSink) {
                    // 保存EventSink以便之后发送事件
                    eventSink = events
                    // 你可以在这里开始发送事件，比如连接到一个传感器或其他数据源
                }

                override fun onCancel(arguments: Any) {
                    // 清理资源，停止发送事件
//                eventSink = null
                }
            })

        } catch (e: java.lang.Exception) {
            Log.d(tag, "EventChannel异常--")
        }

    }

    ///====================================================================================================================
    /**
     * 配置BasicMessageChannel
     */
    private fun configBasicMessageChannel() {
        basicMessageChannel = BasicMessageChannel(flutterEngine!!.dartExecutor.binaryMessenger, "com.test.basic", StringCodec.INSTANCE);
        basicMessageChannel.setMessageHandler { message, reply ->
            run {
                // 处理收到的消息
                d(tag, "收到Flutter消息 " + message);
                // 回复一个消息
                reply.reply("Reply from Java: received");
                sendMessage("Reply from Java: received");
            }
        }
    }

    /**
     * MethodChannel 用法
     */
    private fun configMethodChannel(){
        methodChanel= MethodChannel(flutterEngine!!.dartExecutor.binaryMessenger,"com.test.method");
        methodChanel.setMethodCallHandler { call, result ->
            run {
                if (call.method == "test") {//test方法回应
                    result.success("Hi your argument:"+call.arguments);
                } else {
                    result.notImplemented()
                }

            }
        }
    }

    /***
     * 通过basicMessage Channel 发送消息
     */
    private fun sendMessage(message: String) {
        basicMessageChannel.send(message) { reply: String? ->
            // 处理Dart回复的消息
            d("MainActivity", "Received reply: $reply")
        }
    }

    // 一个示例方法，用于发送事件到Flutter
    private fun sendEventToFlutter(event: String) {
        if (eventSink != null) {
            eventSink!!.success(event)
        }
    }


}